<!DOCTYPE html>
          <head>
        <meta charset="utf-8">
            
            <title>
                「Java」Java中获取本地IP和Port | ttdevs
            </title>
            <meta content="width=device-width, initial-scale=1" name="viewport">
            <meta name="theme-color" content="#4184f3">
            
            
            <link href="/favicon.ico" rel="icon"/>
            

            <link rel="stylesheet" href="/css/highlight.light.css">
            <link rel="stylesheet" href="/css/prism-customize.css">
            <link rel="stylesheet" href="/css/nav-icon.css">
            <link rel="stylesheet" href="/css/waves.min.css">
            <link rel="stylesheet" href="/css/jquery.tocify.css">
            <link rel="stylesheet" href="/css/main.css">
            <link rel="stylesheet" href="/css/nav-indicator.css">
            
  

  
  <!-- 谷歌统计 -->
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-97465173-1', 'auto');
    ga('send', 'pageview');

  </script>
  
            </meta>
        </meta>
    </head>

    <body>
        <header>
            <!-- cover image or sth. -->
        </header>
        <div id="main" class="m-scene">
            
<div class="nav-wrapper">

    <div class="container">
        <nav>
            <div class="logo wave">
                <a href="/" id="logo">
                    ttdevs
                </a>
            </div>
            <div class="nav-toggle-icon" >
                <div class="material-hamburger">
                    <span>
                    </span>
                    <span>
                    </span>
                    <span>
                    </span>
                </div>
            </div>
            <div class="menu-wrapper">
                <div class="nav-indicator">
                </div>
                <ul class="menus">
                    
                     
                        <li>
                            <a class="wave " href="/">
                                首页
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/archives">
                                归档
                            </a>
                        </li>
                     
                        <li>
                            <a class="wave " href="/about">
                                关于
                            </a>
                        </li>
                     
                    
                   
                </ul>
            </div>
        </nav>
    </div>
</div>
            <div class="container content">
                <div class="scene_element scene_element--fadein">
                    <div class="row">
    <div class="main">
        <article>
          
          <header class="post-header with-cover" style="background-image:url('/1970/01/01/[Java]Java中获取本地IP和Port/cover.jpg')" >
          
          </header>
          <h1 class="post-title">「Java」Java中获取本地IP和Port</h1>

          <section class="post-info">
            <span class="post-date">1970/01/01</span>
            
            <span class="post-category">
                <a class="article-category-link" href="/categories/技术/">技术</a>
            </span>
            
            
            <span class="post-tags">
              <ul class="post-tag-list"><li class="post-tag-list-item"><a class="post-tag-list-link" href="/tags/Java/">Java</a></li></ul>
            </span>
            
          </section>

          <section class="post-content">
            <h2 id="0x00-问题"><a href="/1970/01/01/[Java]Java中获取本地IP和Port/#0x00-问题" class="headerlink" title="0x00 问题"></a>0x00 问题</h2><p>项目中要用到DatagramSocket，同时也要获取本地的IP和PORT，直接创建并获取端口获取的IP总是0.0.0.0，代码如下：</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div></pre></td><td class="code"><pre><div class="line">private static void testGetDatagramSocket() &#123;</div><div class="line">	try &#123;</div><div class="line">		DatagramSocket socket = new DatagramSocket();</div><div class="line">		System.out.println(socket.getLocalSocketAddress());</div><div class="line">		socket.close();</div><div class="line">	&#125; catch (SocketException e) &#123;</div><div class="line">		e.printStackTrace();</div><div class="line">	&#125;</div><div class="line">&#125;</div><div class="line">``` </div><div class="line"></div><div class="line">输出结果：</div><div class="line"></div><div class="line">`0.0.0.0/0.0.0.0:55816`</div><div class="line"></div><div class="line"></div><div class="line">## 0x01 解决</div><div class="line"></div><div class="line">查了些资料，比如查询可用端口并绑定，没有现成方法，好像实现不了。个中原因也没太多时间去细究，好像是还没和网卡关联（纯属个人YY）。由于项目对本地端口没有特别</div><div class="line">要求，自己写了一个方法获取DatagramSocket，如下：</div><div class="line"></div><div class="line">``` java</div><div class="line">/**</div><div class="line"> * 从最大端口开始向下遍历，有可能端口就返回</div><div class="line"> *</div><div class="line"> * @return DatagramSocket, 为null的可能性极小</div><div class="line"> */</div><div class="line">public static DatagramSocket getDatagramSocket() &#123;</div><div class="line">    DatagramSocket socket = null;</div><div class="line">    int port = 65535;</div><div class="line">    while (port &gt; 0) &#123;</div><div class="line">        try &#123;</div><div class="line">            socket = new DatagramSocket(new InetSocketAddress(InetAddress.getLocalHost(), --port));</div><div class="line">            System.out.println(port);</div><div class="line">            break;</div><div class="line">        &#125; catch (SocketException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">            continue;</div><div class="line">        &#125; catch (UnknownHostException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">            continue;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    return socket;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>出现异常继续运行，代价使用者自行斟酌。</p>
<h2 id="0x02-测试"><a href="/1970/01/01/[Java]Java中获取本地IP和Port/#0x02-测试" class="headerlink" title="0x02 测试"></a>0x02 测试</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainTest</span> </span>&#123;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">        testGetDatagramSocket();</div><div class="line">        testGetUDPSocketInfo();</div><div class="line">        testGetLocalHost();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">testGetDatagramSocket</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            DatagramSocket socket = <span class="keyword">new</span> DatagramSocket();</div><div class="line">            System.out.println(socket.getLocalSocketAddress());</div><div class="line">            socket.close();</div><div class="line">        &#125; <span class="keyword">catch</span> (SocketException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">testGetUDPSocketInfo</span><span class="params">()</span> </span>&#123;</div><div class="line">        DatagramSocket socket = getDatagramSocket();</div><div class="line">        System.out.println(socket.getLocalSocketAddress());</div><div class="line">        socket.close();</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="comment">/**</span></div><div class="line">     * 从最大端口开始向下遍历，有可能端口就返回</div><div class="line">     *</div><div class="line">     * <span class="doctag">@return</span> DatagramSocket, 为null的可能性极小</div><div class="line">     */</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> DatagramSocket <span class="title">getDatagramSocket</span><span class="params">()</span> </span>&#123;</div><div class="line">        DatagramSocket socket = <span class="keyword">null</span>;</div><div class="line">        <span class="keyword">int</span> port = <span class="number">65535</span>;</div><div class="line">        <span class="keyword">while</span> (port &gt; <span class="number">0</span>) &#123;</div><div class="line">            <span class="keyword">try</span> &#123;</div><div class="line">                socket = <span class="keyword">new</span> DatagramSocket(<span class="keyword">new</span> InetSocketAddress(InetAddress.getLocalHost(), --port));</div><div class="line">                System.out.println(port);</div><div class="line">                <span class="keyword">break</span>;</div><div class="line">            &#125; <span class="keyword">catch</span> (SocketException e) &#123;</div><div class="line">                e.printStackTrace();</div><div class="line">                <span class="keyword">continue</span>;</div><div class="line">            &#125; <span class="keyword">catch</span> (UnknownHostException e) &#123;</div><div class="line">                e.printStackTrace();</div><div class="line">                <span class="keyword">continue</span>;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">return</span> socket;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">testGetLocalHost</span><span class="params">()</span> </span>&#123;</div><div class="line">        <span class="keyword">try</span> &#123;</div><div class="line">            InetAddress address = InetAddress.getLocalHost();</div><div class="line">            System.out.println(address.getHostAddress());</div><div class="line">        &#125; <span class="keyword">catch</span> (UnknownHostException e) &#123;</div><div class="line">            e.printStackTrace();</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>

          </section>
        </article>
        

       
        <div class="pager">
          
            <a class="post-prev pager-item" href="/1970/01/01/[玩转树莓派]0x04还我80端口/" >
              <strong class="article-nav-caption">上一篇</strong>
              <p class="post-nav-title">「玩转树莓派」0x04还我80端口</p>
            </a>
          
          
            <a class="post-next pager-item" href="/1970/01/01/[Python]Python中的Thread Local/">
              <strong class="article-nav-caption">下一篇</strong>
              <p class="post-nav-title">「Python」Python中的Thread Local</p>
            </a>
          
        </div>
        

         <!-- comments -->
        <div class="comment-section">
  
    


</div>

    </div>
    
    <aside>
        <div id="toc">
        </div>
    </aside>
    
</div>

                </div>
            </div>
        </div>
        <footer class="footer">
    <p>由<a href="http://hexo.io/" target="_blank">Hexo</a>强力驱动，搭载<a href="https://github.com/wayou/hexo-theme-gstyle">gstyle</a>主题</p>
    <p>
        &copy; 2017 ttdevs
    </p>
</footer>
<script src="/lib/jquery.js"></script>
<script src="/lib/waves.js"></script>
<script src="/lib/jquery-ui.js"></script>
<script src="/lib/jquery.tocify.js"></script>
<script src="/js/main.js"></script>

    </body>
</html>
